#include "LoginDialog.h"
#include "./ui_dialog.h"
#include "MountWidget.h"
#include <QtWidgets>
#include "AuditPlanFun.h"
#include <QTcpSocket>
#include <QStringList>

#include <QTimer>
#include <QEventLoop>
AnalogClock::AnalogClock(QWidget *parent)
    : QWidget(parent)
{
    timer = new QTimer(this);
    connect(timer, &QTimer::timeout, this, QOverload<>::of(&AnalogClock::update));
    timer->start(1000);

    setWindowTitle(tr("Analog Clock"));
    resize(200, 200);
}

void AnalogClock::paintEvent(QPaintEvent *)
{
    static const QPoint hourHand[3] = {
        QPoint(7, 8),
        QPoint(-7, 8),
        QPoint(0, -40)
    };
    static const QPoint minuteHand[3] = {
        QPoint(7, 8),
        QPoint(-7, 8),
        QPoint(0, -70)
    };

    QColor hourColor(127, 0, 127);
    QColor minuteColor(0, 127, 127, 191);

    int side = qMin(width(), height());

    QPainter painter(this);
    painter.setRenderHint(QPainter::Antialiasing);
    painter.translate(width() / 2, height() / 2);
    painter.scale(side / 200.0, side / 200.0);
    painter.setPen(Qt::NoPen);
    painter.setBrush(hourColor);
    painter.save();

    QTime currentTime = QTime::currentTime();

    painter.rotate(30.0 * ((currentTime.hour() + currentTime.minute() / 60.0)));
    painter.drawConvexPolygon(hourHand, 3);
    painter.restore();
    painter.setPen(hourColor);

    for (int i = 0; i < 12; ++i) {
        painter.drawLine(88, 0, 96, 0);
        painter.rotate(30.0);
    }

    painter.setPen(Qt::NoPen);
    painter.setBrush(minuteColor);

    painter.save();
    painter.rotate(6.0 * (currentTime.minute() + currentTime.second() / 60.0));
    painter.drawConvexPolygon(minuteHand, 3);
    painter.restore();
    painter.setPen(minuteColor);

    for (int j = 0; j < 60; ++j) {
        if ((j % 5) != 0)
            painter.drawLine(92, 0, 96, 0);
        painter.rotate(6.0);
    }
}



Dialog::Dialog(QWidget *parent)
    : QDialog(parent)
    , ui(new Ui::Dialog)
{
    ui->setupUi(this);
    w = new Widget();
    QTimer *timer = new QTimer(this);
    connect(timer, &QTimer::timeout, this, &Dialog::updateDisplay);
    timer->start(1000); // 每秒触发一次
    //标题修改
    setWindowTitle("审计移动存储安全平台");
    setWindowIcon(QIcon(":/icons/images/Upan2.png"));
    ui->groupBox->setStyleSheet("QGroupBox { border: none; "
                                "margin-top: 1.5ex; }");
    ui->groupBox_2->setStyleSheet("QGroupBox { background-color: white; "
                                  "border: none; "
                                  "margin-top: 1.5ex; }");


    int groupBoxWidth = ui->groupBox_3->width();
    int groupBoxHeight = ui->groupBox_3->height();
    // 加载背景图片
    QPixmap pixmap11(":/icons/images/login.png");
    // 动态调整背景图片的大小以适应 GroupBox
    QPixmap scaledPixmap = pixmap11.scaled(groupBoxWidth, groupBoxHeight, Qt::IgnoreAspectRatio, Qt::SmoothTransformation);
    // 将 QPixmap 对象转换为字符串路径
    QString scaledPixmapPath = QDir::tempPath() + "/scaledLoginImage.png";
    scaledPixmap.save(scaledPixmapPath);
    // 将背景图片设置为 GroupBox 的背景
    ui->groupBox_3->setStyleSheet(QString("QGroupBox {"
                                          "background-image: url(:/icons/images/login.png);"
                                          "background-position: center center;"
                                          "background-repeat: repeat;" // 设置平铺背景图片
                                          "border: none; "
                                          "margin-top: 1.5ex; "
                                          "}"
                                          "#groupBox_3 {"
                                          "background-image: url(%1);" // 设置动态调整大小的背景图片
                                          "}").arg(scaledPixmapPath));
    // 创建布局管理器
    AnalogClock *analogClock = new AnalogClock(this);
    QVBoxLayout *groupLayout = new QVBoxLayout;
    groupLayout->addWidget(analogClock);
    ui->groupBox_3->setLayout(groupLayout);

    QPixmap pixmap(":/icons/images/logo.png");
//    ui->label_5->setPixmap(pixmap);
//    ui->label_5->setScaledContents(true);

    ui->lineEdit_Name->setStyleSheet("QLineEdit { border: 1px solid #CCCCCC; background-color: transparent; border-radius: 5px;  }"
                                     "QLineEdit:focus { border: 1px solid green; }"
                                     "QLineEdit:hover { border: 1px solid green; }"
                                     "QLineEdit:pressed { border: 1px solid green; }");
    ui->lineEdit_Name->addAction(ui->action_name, QLineEdit::LeadingPosition);

    ui->lineEdit_Pwd->setStyleSheet("QLineEdit { border: 1px solid #CCCCCC; background-color: transparent; border-radius: 5px; }"
                                    "QLineEdit:focus { border: 1px solid green; }"
                                    "QLineEdit:hover { border: 1px solid green; }"
                                    "QLineEdit:pressed { border: 1px solid green; }");
    ui->lineEdit_Pwd->addAction(ui->act_eye, QLineEdit::TrailingPosition);
    ui->lineEdit_Pwd->addAction(ui->action_psd, QLineEdit::LeadingPosition);

    //ui->checkBox_AutMount->setStyleSheet("QCheckBox::indicator:checked { background-color: #E91E63; border-radius: 2px;}");

    QString buttonStyle = "QPushButton { background-color: #ADD8E6; border-radius: 8px; }"
                          "QPushButton:pressed { background-color: #6FAAD8; }";
    // 应用样式表
    ui->btnLogin->setStyleSheet(buttonStyle);
    ui->btnLogin->setAutoDefault(true);
    ui->label->setText("技术支持单位: \n西安电子科技大学青岛计算技术研究院");
    ui->label->setAlignment(Qt::AlignCenter);
}

Dialog::~Dialog()
{
    delete ui;
}

bool Dialog::isRemovableDrive(const QString &drivePath)
{
    UINT driveType = GetDriveType(reinterpret_cast<const TCHAR*>(drivePath.utf16()));
    return driveType == DRIVE_REMOVABLE;
}

bool isPing(QString ipAddress){
    // 创建 QAbstractSocket 对象
    QTcpSocket socket;
    QStringList ipInfo = ipAddress.split(":");
    socket.connectToHost(ipInfo.at(0), ipInfo.at(1).toInt());  // 连接IP地址和端口号，这里是本地主机和80端口
    if(socket.waitForConnected())  // 等待连接成功
    {
        return true;
    }
    return false;
}

// QString getIpAddress1()
// {
//     QString ip = "127.0.0.1";
//     QString appPath  = QCoreApplication::applicationFilePath();
//     appPath.replace("Upan2.exe", "ip.txt");
//     QFile file(appPath);
//     if (!file.open(QIODevice::ReadOnly | QIODevice::Text))
//     {
//         qDebug() << "无法打开文件";

//     }
//     QTextStream in(&file);
//     while (!in.atEnd())
//     {
//         ip = in.readLine();  // 逐行读取数据
//         qDebug() << ip;
//     }
//     return ip;
//     file.close();
// }

void Dialog::on_btnLogin_clicked()
{

//    //===================================
    UsbEncrypt::AuditFun a;

    QString ipInfo = a.getConfigIpAddress();
//    if(!isPing(ipInfo)){
//        QMessageBox::information(nullptr, "登录失败", "网络未连接！");
//        return;
//    }

    QString Name = ui->lineEdit_Name->text();
    QString Pwd = ui->lineEdit_Pwd->text();
    qDebug() << "Name = " << Name.toStdString().c_str();
    qDebug() << "Pwd = " << Pwd.toStdString().c_str();

    if(!a.login(Name.toStdString(), Pwd.toStdString())){

        QMessageBox::information(nullptr, "登录失败", "账号或密码错误，请重新输入！");
    }
    else{
        //具体操作添加。                        
        w->setLogin(true);
        w->show();
        this->hide();
    }

}


void Dialog::on_btnCancel_clicked()
{
    ui->lineEdit_Name->setText("");
    ui->lineEdit_Pwd->setText("");
}

void Dialog::on_act_eye_triggered()
{
    if (ui->lineEdit_Pwd->echoMode() == QLineEdit::Password) {
        // 如果当前为密码格式，则设置为普通可见模式
        QIcon icon(":/icons/images/visibleActive.png");
        // 改变图标大小
        icon = icon.pixmap(QSize(30, 30)); // 这里指定了新的图标尺寸
        ui->act_eye->setIcon(icon);
        ui->lineEdit_Pwd->setEchoMode(QLineEdit::Normal);
    } else {
        // 否则设置为密码格式
        ui->act_eye->setIcon(QIcon(":/icons/images/visible.png"));
        ui->lineEdit_Pwd->setEchoMode(QLineEdit::Password);
    }
}

#include <QPropertyAnimation>
void Dialog::updateDisplay()
{
    // 获取当前时间
    QDateTime currentTime = QDateTime::currentDateTime();
    // 格式化时间为字符串，如 "yyyy-MM-dd hh:mm:ss"
    QString timeString = currentTime.toString("yyyy-MM-dd hh:mm:ss");
    QDateTime dateTime = QDateTime::fromString(timeString, "yyyy-MM-dd hh:mm:ss");
    ui->label_7->setText(dateTime.toString("yyyy年MM月dd日"));
    ui->label_7->setStyleSheet("color: white;");
    ui->label_hm->setText(dateTime.toString("hh:mm"));
    ui->label_hm->setStyleSheet("color: white;");
    ui->label_s->setText(dateTime.toString("ss"));
    ui->label_s->setStyleSheet("color: white;");

    QLocale locale(QLocale::Chinese);
    QDateTime currentDateTime = QDateTime::currentDateTime();
    QLocale chineseLocale(QLocale::Chinese);

    // 将当前日期时间格式化为只包含星期几的字符串
    QString chineseDayOfWeek = chineseLocale.toString(currentDateTime.date(), "dddd");
    ui->label_D->setText(chineseDayOfWeek);
    ui->label_D->setStyleSheet("color: white;");

    //qDebug()<<"timeString="<<timeString;
}

